<template>
  <div >
    <div class="header">
      <img src="static/imgs/homePageImg/home_logo.png" alt="logo" class="logo"/>
      <ul class="userInfo">
        <li v-if="userName" class="userLogo"><img src="static/imgs/homePageImg/home_icon.png" alt="头像"/><span>{{ userName }}</span></li>
        <li v-if="userName" @click="logout">注销</li>
        <li v-if="!userName" @click="login">登录/注册</li>
        <li v-if="header.template" @click="header.templateAction">{{header.template}}</li>
        <li ><router-link to="/help">帮助</router-link></li>
      </ul>
    </div>
    <!--登录注册dialog-->
    <Vdialog
      :visible="dialogVisible"
      :closeDialog="handleClose">
      <!--登录-->
      <div slot="modal-header" class="dialog-Header">
        <div class="logo"><img  src="static/imgs/homePageImg/home_logo.png"/></div>
        <img  class="close" @click="handleClose" src="static/imgs/homePageImg/close.png"/>
      </div>
      <div slot="modal-body" class="dialogBody" v-show="loginVisible === 1">
        <div v-show='loginFail' class="loginError">账号或密码输入错误</div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm1" label-width="120px" class="demo-ruleForm" >
          <el-form-item label="用户名:" prop="username" class="eleForm">
            <el-input v-model="ruleForm.username" ></el-input>
          </el-form-item>
          <el-form-item label="验证码:" prop="code" class="eleForm" style="display: none">
            <el-input type="text" v-model="ruleForm.code"></el-input><span class="getCode">获取验证码</span>
          </el-form-item>
          <el-form-item label="密码:" prop="password" class="eleForm">
            <el-input type="password" v-model="ruleForm.password"></el-input>
          </el-form-item>
          <ul  class="actionLi">
            <li @click="loginSure">登录</li>
            <li class="register" @click="register">注册</li>
            <li class="forgetPassword" @click="forgetPassword">忘记密码？</li>
          </ul>
        </el-form>
      </div>
      <!--注册-->
      <div slot="modal-body" class="dialogBody" v-show="loginVisible === 2">
        <p class="registerTitle">注册</p>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm2" label-width="120px" class="demo-ruleForm">
          <el-form-item label="手机号:" prop="username" class="eleForm">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="验证码:" prop="code" class="eleForm" >
            <el-input  v-model="ruleForm.code"></el-input><span class="getCode" @click="getQRcode">获取验证码</span>
          </el-form-item>
          <el-form-item label="密码:" prop="password" class="eleForm">
            <el-input type="password" v-model="ruleForm.password"></el-input>
          </el-form-item>
          <ul  class="actionLi">
            <li class="register" @click="registerSure">完成</li>
          </ul>
        </el-form>
      </div>
      <!--忘记密码-->
      <div slot="modal-body" class="dialogBody" v-show="loginVisible === 3">
        <p class="registerTitle">忘记密码</p>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm3" label-width="120px" class="demo-ruleForm">
          <el-form-item label="手机号:" prop="username" class="eleForm">
            <el-input v-model="ruleForm.username"></el-input>
          </el-form-item>
          <el-form-item label="验证码:" prop="code" class="eleForm" >
            <el-input type="text" v-model="ruleForm.code"></el-input><span class="getCode">获取验证码</span>
          </el-form-item>
          <el-form-item label="新密码:" prop="password" class="eleForm">
            <el-input type="password" v-model="ruleForm.password"></el-input>
          </el-form-item>
          <ul  class="actionLi">
            <li class="register" @click="forgetPasswordSure">完成</li>
          </ul>
        </el-form>
      </div>
    </Vdialog>
  </div>
</template>

<script>
import Vdialog from './Vdialog'
import { loginAction, logoutAction, registerAction, forgetPasswordAction, getQRcodeAction } from '../../axios/api/homePage_api'
import { getCookie } from '../../axios/utils'
const emptyRuleForm = {
  username: '',
  code: '',
  password: ''
}
export default {
  name: 'Vheader',
  userName: '',
  props: {
    header: {
      type: Object,
      required: true,
      default: () => {}
    }
  },
  data () {
    var validatePhone = (rule, value, callback) => {
      // let phoneReg = /^[1][3-9][0-9]{9}$/
      let phoneReg = /^[0-9A-Za-z]+$/
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (!phoneReg.test(value)) {
        callback(new Error('手机号格式不正确'))
      } else {
        callback()
      }
    }
    var validatePassword = (rule, value, callback) => {
      // let passwordReg = new RegExp(/^[0-9A-Za-z]+$/)
      let passwordReg = new RegExp(/^[0-9A-Za-z]+$/)
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (!passwordReg.test(value)) {
        callback(new Error('密码中必须包含字母、数字，6到30个字符'))
      } else {
        callback()
      }
    }
    return {
      // 控制dialog是否显示，以及显示那个模块的变量
      dialogVisible: false,
      loginVisible: 1,
      loginFail: false,
      ruleForm: Object.assign({}, emptyRuleForm), // 是为了防止其他数据改变emptyRuleForm的数据
      rules: {
        username: [
          { required: true, validator: validatePhone, trigger: 'blur' }
        ],
        password: [
          { required: true, validator: validatePassword, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    let islogin = this.$route.query.isLogin
    if (islogin === false) {
      document.cookie = 'username='
      this.$message({
        type: 'info',
        message: '请登录'
      })
    } else {
      this.userName = getCookie('username')
      this.$store.commit('SET_USER', this.userName)
    }
  },
  components: {
    Vdialog
  },
  methods: {
    // 点击登录/注册弹出dialog
    login () {
      this.$refs['ruleForm1'].resetFields()
      this.ruleForm = Object.assign({}, emptyRuleForm)
      this.dialogVisible = true
      this.loginVisible = 1
      this.loginFail = false
      this.rules.code[0].required = false
    },
    logout () {
      let that = this
      this.$confirm('此操作将注销用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.userName = ''
        this.$store.commit('SET_USER', '')
        document.cookie = 'username='
        that.logoutSure()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消注销'
        })
      })
    },
    async logoutSure () {
      let { data } = await logoutAction()
      if (data.code === 1) {
        this.$message({
          message: '注销成功',
          type: 'success'
        })
        location.reload()
        this.$router.push({name: 'homePage'})
      } else {
        this.$message({
          message: '注销失败',
          type: 'error'
        })
      }
    },
    // 关闭dialog
    handleClose () {
      this.dialogVisible = false
    },
    // 跳转到注册页面
    register () {
      this.$refs['ruleForm2'].resetFields()
      this.loginVisible = 2
      this.ruleForm = Object.assign({}, emptyRuleForm)
      this.rules.code[0].required = true
    },
    // 跳转到忘记密码页面
    forgetPassword () {
      this.$refs['ruleForm3'].resetFields()
      this.rules.code[0].required = true
      this.loginVisible = 3
      this.ruleForm = Object.assign({}, emptyRuleForm)
    },
    // 登录
    loginSure () {
      this.$refs['ruleForm1'].validate(async valid => {
        if (valid) {
          let { data } = await loginAction(this.ruleForm)
          if (data.code === 1) {
            this.dialogVisible = false
            this.$message({
              message: '登录成功',
              type: 'success'
            })
            this.userName = this.ruleForm.username
            this.$store.commit('SET_USER', this.ruleForm.username)
            document.cookie = 'username=' + this.ruleForm.username
          } else {
            this.loginFail = true
          }
        } else {
          return false
        }
      })
    },
    // 注册
    registerSure () {
      this.$refs['ruleForm2'].validate(async valid => {
        if (valid) {
          try {
            let { data } = await registerAction(this.ruleForm)
            if (data.code === 1) {
              this.userName = this.ruleForm.username
              this.$store.commit('SET_USER', this.ruleForm.username)
              document.cookie = 'username=' + this.ruleForm.username
              this.$message({
                message: '注册成功',
                type: 'success'
              })
            } else {
              this.$message.error('注册失败')
            }
          } finally {
            this.dialogVisible = false
          }
        } else {
          return false
        }
      })
    },
    // 找回密码
    async forgetPasswordSure () {
      this.$refs['ruleForm3'].validate(async valid => {
        if (valid) {
          try {
            let { data } = await forgetPasswordAction(this.ruleForm)
            if (data.code === 1) {
              this.userName = this.ruleForm.username
              this.$store.commit('SET_USER', this.ruleForm.username)
              document.cookie = 'username=' + this.ruleForm.username
              this.$message({
                message: '找回密码成功',
                type: 'success'
              })
            } else {
              this.$message.error('找回密码失败')
            }
          } finally {
            this.dialogVisible = false
          }
        } else {
          return false
        }
      })
    },
    async getQRcode () {
      let { data } = await getQRcodeAction({ phoneNumber: this.ruleForm.username })
      if (data.code === 1) {
        this.$message({
          message: '发送成功',
          type: 'success'
        })
        // location.reload()
        this.$router.push({name: 'homePage'})
      } else {
        this.$message({
          message: '注销失败',
          type: 'error'
        })
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .header{
    height: 54px;
    background-color: #000;
    opacity: 0.75;
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    font-size: 20px;
  }
  .userInfo{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
  }
  .userInfo li{
    padding: 12px 10px;
    color: #fff;
  }
  .userInfo li:not(.userLogo){
    cursor: pointer;
  }
  .userInfo li:hover:not(.userLogo){
    background-color: #47cb69;
  }
  .userInfo li a{
    color: #fff;
  }
  .userInfo li a:hover{
    text-decoration: none;
  }
  .userLogo{
    cursor: default;
  }
  .userLogo span {
    display: inline-block;
    margin-top: -30px;
    margin-left: 10px;
  }
  .userLogo img {
    margin-top: -4px;
  }
  /*dialog样式*/
  .dialog-Header{
     height: 73px;
      background-color: #000;
      opacity: 0.75;
      display: flex;
      flex-direction: row;
    }
  .dialog-Header .logo{
    align-self:center;
    flex: 1;
  }
  .dialog-Header .close{
    align-self:center;
    margin-right: 25px;
  }
  .dialogBody{
    margin-right: 141px;
    margin-top: 74px;
  }
  .actionLi{
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    margin-left: 143px;
  }
  .actionLi li{
    width: 306px;
    background-color: #47cb69;
    height: 30px;
    margin-bottom: 38px;
    font-size: 20px;
    border-radius: 3px;
    color: white;
    padding: 5px;
    cursor: pointer;
  }
  .actionLi li.forgetPassword{
    background-color: white;
    color: #47cb69;
    margin-bottom: 34px;
  }
  .actionLi li.register{
    background-color: white;
    color: #47cb69;
    border: 1px solid #47cb69;
  }
  /*注册表，忘记密码样式*/
  .registerTitle{
    font-size: 48px;
    color: #47cb69;
    margin: -48px 0 10px 143px;
  }

  .loginError{
    color: red;
    font-size: 18px;
    margin-top: -37px;
    margin-bottom: 10px;
  }
</style>
<style>
  .dialogBody .eleForm{
    height: 30px;
    margin-bottom: 48px;
    font-size: 20px;
    color: #a7a7a7;
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
  }
  .eleForm label{
    font-size: 20px;
    margin-right: -120px;
  }
  .eleForm input{
    border: 1px solid #ccc;
    height: 39px;
    background-color:rgb(233,233,231);
    width: 316px;
    padding: 5px;
    border-radius: 3px;
    margin-left: 10px;
    font-size: 18px;
  }
  .getCode{
    display: inline-block;
    margin-left: -117px;
    height: 34px;
    width: 117px;
    font-size: 20px;
    border-radius: 3px;
    color: white;
    background-color: #47cb69;
    padding-bottom: 3px;
    margin-top: 3px;
    cursor: pointer;
    z-index: 2;
    position: absolute;
  }
  .eleForm .el-input__inner:focus{
    border-color: #47cb69
  }
  .eleForm .el-form-item__error{
    padding-top: 20px;
    padding-left: 9px;
  }
</style>
